<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <title>发送邮件</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/other/common.css}"/>
</head>
<body>
<form class="layui-form" action="">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">收件人分组</label>
                <div class="layui-input-block">
                    <select name="groupId" id="group" lay-verify="required" lay-filter="group">
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">收件人列表</label>
                <div class="layui-input-block">
                    <div id="recipientList"
                         style="width: 100%;height: 100px;overflow: auto;border: 1px solid #eee"></div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">主题</label>
                <div class="layui-input-block">
                    <input type="text" name="subject" required lay-verify="required" placeholder="请输入主题"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">选择文章</label>
                <div class="layui-input-block" style="display: flex;justify-content: flex-start">
                    <div class="layui-col-md4">
                        <input type="text" id="parent-tree-input" placeholder="请选择栏目" class="layui-input"
                               readonly="readonly" lay-verify="required">
                        <input type="hidden" name="channelId" id="parentName"/>
                        <div id="parent-tree"
                             style="display:none; position: absolute; z-index: 1000; background-color: #fff; border: 1px solid #d2d2d2; width: 100%; max-height: 300px; overflow-y: auto;"></div>
                    </div>
                    <div class="layui-col-md8" id="templateWrapper" style="position: relative;z-index: 1001">
                        <select id="selectArticle" name="articleId" lay-verify="required" lay-filter="article"
                                lay-search>
                            <option value="">请选择文章</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">内容</label>
                <div class="layui-input-block">
                    <script id="uEditor" name="content" type="text/plain" style="width:100%;height:400px;"></script>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">附件</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn demo-class-accept" lay-options="{accept: 'file'}">
                        <i class="layui-icon layui-icon-upload"></i>
                        上传附件
                    </button>
                    <input type="hidden" name="emailAttachment">
                    <span id="file_p"></span>
                    <a id="removeAttachment" style="cursor: pointer;display: none">
                        <i class="layui-icon layui-icon-delete"></i>
                    </a>
                    <div style="width: 117px;margin-top: 10px">
                        <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo1">
                            <div class="layui-progress-bar" lay-percent=""></div>
                        </div>
                    </div>
                    <p style="margin-top:3px;color:red;font-size: 15px">
                        注意：仅支持上传压缩包文件 (zip, rar, 7z, tar, gz)
                    </p>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-success layui-btn" lay-submit=""
                    lay-filter="email-edit" id="email-edit">
                <i class="layui-icon layui-icon-ok"></i>
                保存
            </button>
            <button type="reset" class="layui-btn layui-btn" id="email-reset">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:src="@{/pear/component/ueditor/ueditor.config.js}"></script>
<script th:src="@{/pear/component/ueditor/ueditor.all.js}"></script>
<script th:src="@{/pear/component/ueditor/lang/zh-cn/zh-cn.js}"></script>
<script th:inline="javascript">
    layui.use(function () {
        let form = layui.form;
        let tree = layui.tree;
        let element = layui.element;
        let upload = layui.upload;
        let $ = layui.jquery;
        let layer = layui.layer;
        let baseURL = /*[[@{/}]]*/ '';
        let ue = UE.getEditor('uEditor', {
            serverUrl: baseURL + 'cms/ueditor/upload',
            autoFloatEnabled: false,  // 解决工具栏粘顶问题
        });
        $(document).ready(function () {
            getChannelTree();
            getGroup();
        })
        if (parent.state !== 0) {
            $('#email-edit').hide();
            $('#email-reset').hide();
        }
        //选择收件人分组
        let getGroup = function () {
            $.ajax({
                url: baseURL + "cms/group/getGroupList",
                type: 'GET',
                success: function (res) {
                    if (res.code === 1000) {
                        let groupSelect = $('#group');
                        groupSelect.empty();
                        groupSelect.append('<option value="">请选择收件人分组</option>');
                        $.each(res.data, function (index, item) {
                            groupSelect.append('<option value="' + item.id + '">' + item.groupName + '</option>');
                        });
                        if (parent.nowGroupId) {
                            groupSelect.val(parent.nowGroupId);
                            getRecipientList(parent.nowGroupId)
                        }
                        form.render('select');
                    }
                }
            })
        }
        form.on('select(group)', function (data) {
            let groupId = data.value;
            if (groupId) {
                getRecipientList(groupId)
            }
        })

        let getRecipientList = function (groupId) {
            $.ajax({
                url: baseURL + "cms/recipient/recipientListByGroupId",
                type: 'GET',
                data: {
                    groupId: groupId
                },
                success: function (res) {
                    if (res.code === 1000) {
                        let recipientList = $('#recipientList');
                        recipientList.empty();
                        $.each(res.data, function (index, item) {
                            recipientList.append('<span style="white-space: nowrap;margin-left: 5px;"><span>'
                                + item.name + '</span><span style="color: #A0A0A0">&lt;'
                                + item.email + '&gt;;</span></span>');
                        });
                    }
                },
                error: function (res) {
                    console.error(res.msg);
                }
            })
        }
        let initChannelAndArticle = function (data) {
            $('#parentName').val(parent.nowChannelId)
            let title = findTitlesById(data, parent.nowChannelId)
            $('#parent-tree-input').val(title);
            getArticles(parent.nowChannelId)
        }
        let findTitlesById = function (data, targetId) {
            for (let item of data) {
                if (item.id === targetId) {
                    return item.title;
                }

                if (item.children && item.children.length > 0) {
                    const result = findTitlesById(item.children, targetId);
                    if (result) {
                        return result;
                    }
                }
            }
        }
        //选择栏目、文章
        let getChannelTree = function () {
            // 初始化树形结构的隐藏状态
            $('#parent-tree').hide();
            // 点击输入框时显示树形结构
            $('#parent-tree-input').on('click', function () {
                $('#parent-tree').toggle(); // 显示或隐藏树形结构
            });
            // 渲染父级栏目树形结构
            $.get(baseURL + "cms/channel/getParentMenus", function (data) {
                initChannelAndArticle(data)
                tree.render({
                    elem: '#parent-tree', // 树形组件容器
                    data: data, // 后端返回的树形数据
                    click: function (obj) {
                        if (obj && obj.data) {
                            ue.setContent('');
                            $('#parent-tree-input').val(obj.data.title); // 填充栏目名称
                            $('#parentName').val(obj.data.id); // 填充栏目ID
                            getArticles(obj.data.id)
                            $('#parent-tree').hide(); // 隐藏树形选择框
                        } else {
                            console.error("无法获取节点数据");
                        }
                    }
                });
            });
            // 点击空白区域时，关闭树形选择框
            $(document).on('click', function (e) {
                if (!$(e.target).closest('#parent-tree-input').length && !$(e.target).closest('#parent-tree').length) {
                    $('#parent-tree').hide();
                }
            });
        }
        let getArticles = function (channelId) {
            let articleSelect = $('#selectArticle');
            articleSelect.empty();
            $.ajax({
                url: baseURL + "cms/infoArticle/getArticlesByChannelId",
                type: 'GET',
                data: {channelId: channelId},
                success: function (res) {
                    if (res.code === 1000) {
                        articleSelect.append('<option value="">请选择文章</option>');
                        res.data.forEach(item => {
                            const option = document.createElement('option');
                            option.value = item.articleId;
                            // 安全地插入标题内容，避免 XSS
                            option.textContent = item.title;  // 使用 textContent 避免 HTML 解析
                            articleSelect.append(option);
                        });
                        // 显示模板内容下拉框并渲染
                        $('#templateWrapper').show();
                        $.ajax({
                            url: baseURL + "cms/email/getEmailById?id=" + parent.id,
                            type: 'GET',
                            success: function (res) {
                                const decodedData = atob(res.data.content);
                                let c = new TextDecoder('utf-8').decode(new Uint8Array([...decodedData].map(char => char.charCodeAt(0))));
                                ue.setContent(c);
                            }
                        })
                        form.render('select');
                    }

                },
                error: function () {
                    console.error("请求失败");
                }
            });
        }
        let getContentById = function (articleId) {
            $.ajax({
                url: baseURL + "cms/infoArticle/getContentById",
                type: 'GET',
                data: {articleId: articleId},
                success: function (res) {
                    console.log(res.data)
                    if (res.code === 1000) {
                        const decodedData = atob(res.data.content);
                        let c = new TextDecoder('utf-8').decode(new Uint8Array([...decodedData].map(char => char.charCodeAt(0))));
                        ue.setContent(c);
                    }
                },
                error: function () {
                    console.error("请求失败");
                }
            })
        }
        form.on('select(article)', function (data) {
            let articleId = data.value;
            if (articleId) {
                getContentById(articleId)
            } else {
                ue.setContent('');
            }
        });


        //附件上传
        let uploadAttachment = upload.render({
            elem: '.demo-class-accept',
            url: baseURL + 'cms/email/uploadAttachment',
            accept: 'file',
            exts: 'zip|rar|7z|tar|gz',
            size: 200 * 1024,
            before: function (obj) {
                element.progress('filter-demo1', '0%');
                layer.msg('上传中', {icon: 16, time: 0});
            },
            done: function (res) {
                if (res.code === 1000) {
                    $("[name=emailAttachment]").val(res.data);
                    const fileName = res.data.split('/').pop().split('_').slice(1).join('_');
                    $('#file_p').html(`${fileName}
                        <a href="${baseURL}${res.data}" download="${fileName}" style="margin-left: 10px; color: #1e9fff;">
                        点击下载查看附件
                        </a>
                    `);
                    $('#removeAttachment').show();
                    layer.msg('上传完毕', {icon: 1, time: 2000});
                    return;
                }
                $('#file_p').html('上传失败，请重试！').css('color', 'red');
                element.progress('filter-demo', '0%');
                layer.msg(res.msg, {icon: 2, time: 2000});
            }, progress: function (n) {
                element.progress('filter-demo1', n + '%');
            }
        })
        $('#removeAttachment').on('click', function () {
            layer.confirm('确定要删除附件吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                element.progress('filter-demo', '0%');
                $("[name=emailAttachment]").val('');
                $('#file_p').html('');
                $('#removeAttachment').hide()
            })
        });

        // 表单提交
        form.on('submit(email-edit)', function (data) {
            let loading = layer.msg('邮件保存中', {icon: 16, shade: 0.3, time: 0});
            data.field.id = parent.id
            data.field.content = btoa(unescape(encodeURIComponent(data.field.content)));
            $.ajax({
                url: baseURL + 'cms/email/update',
                data: JSON.stringify(data.field),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    layer.close(loading);
                    if (result.code === 1000) {
                        layer.msg(result.msg, {
                            icon: 1,
                            time: 2000
                        }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            parent.layui.table.reload("email-table");
                        });
                    } else {
                        layer.msg(result.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                },
                error: function () {
                    layer.close(loading);
                    layer.msg('服务器错误，请稍后再试！', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
            return false;
        });
    });
</script>
</body>
</html>